<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- tips -->
      <el-alert title="添加商品信息" type="info" show-icon :closable="false" center ></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="商品信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏切换 -->
      <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeLeaveTabs" @tab-click="tabClick">
        <el-tab-pane label="商品信息" name="0">
          <el-form :model="addForm" :rules="addRules" ref="addRuleForm" label-width="100px" class="demo-ruleForm" label-position="top">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price" type="number">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" type="number">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" type="number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="{ expandTrigger: 'hover', value: 'cat_id',  label: 'cat_name'}" @change="handleChange"></el-cascader>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-form>
            <el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="checkValue" v-for="(checkValue, i) in item.attr_vals" :key="i" border size="medium"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form>
            <el-form-item :label="item.attr_name" prop="goods_price" type="number" v-for="item in onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            class="upload-demo"
            action="http://127.0.0.1:8888/api/private/v1/upload"
            :headers= headers
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-preview="handlePreview"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <quill-editor v-model="addForm.goods_introduce"></quill-editor>
          <el-button type="primary" @click="add">提交</el-button>
        </el-tab-pane>
      </el-tabs>
      <!-- 图片预览 -->
      <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
         <el-image :src="imageSrc"></el-image>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
export default {
  name: 'GoodsAdd',
  components: {
    quillEditor
  },
  data () {
    return {
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [],
        attrs: [],
        goods_introduce: ''
      },
      addRules: {
        goods_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      cateList: [],
      manyData: [],
      onlyData: [],
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      dialogVisible: false,
      imageSrc: ''
    }
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      } else {
        return null
      }
    }
  },
  created () {
    this.getCateData()
  },
  methods: {
    // 获取分类列表
    async getCateData () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status === 200) {
        this.cateList = res.data
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    handleChange () {},
    // tab栏切换前
    beforeLeaveTabs (activeName, oldActiveName) {
      // 商品信息
      if (oldActiveName === '0') {
        if (this.addForm.goods_cat.length === 3) {
          return true
        } else {
          this.$message.error('商品分类只能选择第三级')
          return false
        }
      }
    },
    // tab切换
    async tabClick (v) {
      // 商品参数
      if (v.name === '1' && this.addForm.goods_cat.length === 3) {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status === 200) {
          this.manyData = res.data
          this.manyData.map(v => {
            v.attr_vals = v.attr_vals ? v.attr_vals.split(',') : []
          })
        } else {
          this.$message.error(res.meta.msg)
        }
      } else if (v.name === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status === 200) {
          this.onlyData = res.data
        } else {
          this.$message.error(res.meta.msg)
        }
      }
    },
    // 删除文件上传
    handleRemove (file) {
      const index = this.addForm.pics.indexOf(file.response.data.tmp_path)
      this.addForm.pics.splice(index, 1)
    },
    // 上传成功时回调
    handleSuccess (file) {
      const item = {
        pic: file.data.tmp_path
      }
      this.addForm.pics.push(item)
    },
    // 上传图片预览
    handlePreview (file) {
      this.dialogVisible = true
      this.imageSrc = file.response.data.url
    },
    // 提交
    async add () {
      this.$refs.addRuleForm.validate(async valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(this.addForm))
          form.goods_cat = form.goods_cat.join(',')
          this.manyData.map(item => {
            const v = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(',')
            }
            form.attrs.push(v)
          })
          this.onlyData.map(item => {
            const v = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            form.attrs.push(v)
          })
          const { data: res } = await this.$http.post('goods', form)
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg)
            this.$router.push('/goods')
          } else {
            this.$message.success(res.meta.msg)
          }
        } else {
          this.$message.error('请填写必要信息')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .el-steps {
    margin: 40px 0;
    /deep/.el-step__title {
      font-size: 12px;
    }
  }
  .el-checkbox {
    margin: 0 10px 0 0;
  }
  /deep/.ql-editor {
    min-height: 400px;
  }
  /deep/.quill-editor {
    margin-bottom: 20px;
  }
</style>
